package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁：是一种思想，基于ReentrantLock实现当ReentrantLock传入true的时候就是公平锁：
 *
 * 公平锁：多个线程按照申请锁的顺序来获取锁，类似于排队买票，先来后到，按照FIFO的原则从队列中拿到线程，然后占有锁。。
 *
 */
public class FairLockAndUnjustExample {
    // 公平锁
    ReentrantLock lock = new ReentrantLock(true); // 创建公平锁

    //非公平锁
    ReentrantLock lock2 = new ReentrantLock(); // 创建非公平锁，默认就是非公平


    //公平锁的实现方法
    public void criticalSectionFairLock() {
        lock.lock();  // 获取锁
        try {
            System.out.println(Thread.currentThread().getName() + " is in critical section.");
            Thread.sleep(1000);  // 模拟一些操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();  // 释放锁
        }
    }

    //非公平锁实现方法
    public void criticalSectionUnjusLock() {
        lock2.lock();  // 获取锁
        try {
            System.out.println(Thread.currentThread().getName() + " is in critical section.");
            Thread.sleep(1000);  // 模拟一些操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock2.unlock();  // 释放锁
        }
    }

    public static void main(String[] args) {
        FairLockAndUnjustExample example = new FairLockAndUnjustExample();

        // 启动多个线程来争夺锁
        Thread t1 = new Thread(example::criticalSectionFairLock);
        Thread t2 = new Thread(example::criticalSectionFairLock);
        Thread t3 = new Thread(example::criticalSectionFairLock);

        t1.start();
        t2.start();
        t3.start();
    }
}
